import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/ex/string_ex.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_widgets/widgets/checkbox/kq_checkbox.dart';

import '../../../config/kq_global.dart';
import '../../../resources/images.dart';
import '../../../resources/kq_theme_colors.dart';
import '../../../resources/l10n/kq_intl.dart';
import '../../../theme/kq_theme_manager.dart';
import '../../button/kq_icon_button.dart';
import '../../divider/kq_divider.dart';
import '../../searchBar/kq_search_bar.dart';

/// 底部弹出-列表选择
///
/// @author 周卓
///
class KqListPickerBottomSheet<T> extends StatelessWidget {
  /// 标题
  final String? title;

  /// 数据源
  final List<T> items;

  ///选中的数据
  final String? chooseIds;

  /// 转换 T -> name 转换
  final String Function(int index, T item)? nameConvert;

  /// 转换 T -> itemId 转换
  final String Function(int index, T item)? idConvert;

  /// 回调
  final Function(int index, T item)? callback;

  /// 多选回调
  final Function(List<T> items, bool isSelectAll)? callbackMulti;

  /// 是否多选，默认false
  final bool isMultiChoose;

  /// 是否显示搜索，[searchEnable]=true时，需要配合[onSearchItem]使用，默认false
  final bool searchEnable;

  /// 搜索内容匹配方法，仅[searchEnable]=true时生效
  final bool Function(String searchText, T item)? onSearchItem;

  const KqListPickerBottomSheet(
      {Key? key,
      required this.items,
      this.title,
      this.searchEnable = false,
      this.isMultiChoose = false,
      this.chooseIds,
      this.callbackMulti,
      this.idConvert,
      this.onSearchItem,
      this.nameConvert,
      this.callback})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    var padding = MediaQuery.of(context).viewInsets.bottom;
    return Padding(
      padding: EdgeInsets.only(bottom: padding),
      child: SizedBox(
          width: 414.r,
          child: Material(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(8.r),
                      topRight: Radius.circular(8.r))),
              color: KqThemeManager.instance
                      .getConfig()
                      .dialogConfig
                      .bottomSheetBgColor ??
                  KqThemeColors.bgF5,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  if (title.isNotNullOrEmpty)
                    Stack(
                      children: [
                        Container(
                          alignment: Alignment.center,
                          width: double.infinity,
                          height: 48.r,
                          child: Text(
                            title ?? '',
                            style: TextStyle(
                                fontSize: 16.sp, color: KqThemeColors.text26),
                          ),
                        ),
                        Positioned(
                          right: 8.r,
                          child: KqIconButton(
                            size: 48.r,
                            onPressed: () => Navigator.pop(context),
                            icon: Image.asset(
                              Images.commonIcGuanbi,
                              height: 44.r,
                              width: 44.r,
                              package: KqGlobal.packageName,
                            ),
                          ),
                        )
                      ],
                    ),
                  Container(
                    margin:
                        EdgeInsets.only(top: title.isNullOrEmpty ? 16.r : 4.r),
                    child: KqSearchBottomListView(
                      items: items,
                      radius: 4.r,
                      fontSize: 14.sp,
                      paddingBottom: padding,
                      searchEnable: searchEnable,
                      onSearchItem: onSearchItem,
                      isMultiChoose: isMultiChoose,
                      nameConvert: nameConvert,
                      idConvert: idConvert,
                      callback: callback,
                      chosenIds: chooseIds,
                      callbackMulti: callbackMulti,
                    ),
                  ),
                ],
              ))),
    );
  }
}

/// 地步搜索列表
class KqSearchBottomListView<T> extends StatefulWidget {
  /// 数据源
  final List<T> items;

  /// 是否显示搜索，默认不显示
  final bool searchEnable;

  /// 是否多选
  final bool isMultiChoose;

  /// 转换 T -> String 转换
  final String Function(int index, T item)? nameConvert;

  /// 已选择的ids
  final String? chosenIds;

  /// 转换 T -> String 转换
  final String Function(int index, T item)? idConvert;

  /// 搜索内容匹配方法，仅[searchEnable]=true时生效
  final bool Function(String searchText, T item)? onSearchItem;

  /// 回调
  final Function(int index, T item)? callback;

  /// 多选回调
  final Function(List<T> items, bool isSelectAll)? callbackMulti;

  /// 圆角大小，默认8
  final double? radius;

  /// 字体大小，默认16
  final double? fontSize;

  /// 底部padding
  final double paddingBottom;

  const KqSearchBottomListView(
      {Key? key,
      required this.items,
      this.onSearchItem,
      this.searchEnable = false,
      this.isMultiChoose = false,
      this.nameConvert,
      this.chosenIds,
      this.idConvert,
      this.radius,
      this.paddingBottom = 0,
      this.fontSize,
      this.callbackMulti,
      this.callback})
      : super(key: key);

  @override
  KqSearchBottomListViewState createState() => KqSearchBottomListViewState<T>();
}

class KqSearchBottomListViewState<T> extends State<KqSearchBottomListView<T>> {
  /// 搜索内容
  var _searchText = "";

  List<T> _allItems = [];

  List<T> _showItems = [];

  ///多选选择的items
  List<T> _chooseItems = [];

  bool _isChooseAll = false;

  @override
  void initState() {
    _allItems = widget.items;
    _showItems = [..._allItems];
    _initChosenData();
    super.initState();
  }

  _initChosenData() {
    if (widget.chosenIds.isNotNullOrEmpty && widget.isMultiChoose) {
      //存在数据
      var list = widget.chosenIds!.split(',');
      for (var i = 0; i < list.length; i++) {
        for (var j = 0; j < _showItems.length; j++) {
          String id = widget.idConvert != null
              ? widget.idConvert!.call(j, _showItems[j])
              : '';
          if (list[i] == id) {
            _chooseItems.add(_showItems[j]);
            break;
          }
        }
      }
    }
  }

  @override
  void didUpdateWidget(covariant KqSearchBottomListView<T> oldWidget) {
    if (oldWidget.items != widget.items) {
      _allItems = widget.items;
      searchData(update: false);
    }
    if (widget.chosenIds != oldWidget.chosenIds) {
      _initChosenData();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    // 小诸葛规范，最多显示6个，多余滚动

    final List<Widget> children = <Widget>[];

    /// item
    for (int i = 0; i < _showItems.length; i++) {
      var item = _showItems[i];
      String title;
      if (widget.nameConvert != null) {
        title = widget.nameConvert!(i, item);
      } else {
        if (item is String) {
          title = item;
        } else if (item is Map) {
          title = item['title'];
        } else {
          title = '';
        }
      }
      children.add(KqInkWell(
        onTap: () {
          if (widget.isMultiChoose) {
            if (_chooseItems.contains(item)) {
              _chooseItems.remove(item);
            } else {
              _chooseItems.add(item);
            }
            _isChooseAll = _chooseItems.length == _allItems.length;
            setState(() {});
          } else {
            widget.callback?.call(i, item);
          }
        },
        child: Container(
          height: 48.r,
          alignment: Alignment.centerLeft,
          width: double.infinity,
          padding: EdgeInsets.symmetric(vertical: 0, horizontal: 16.r),
          child: Row(
            children: [
              if (widget.isMultiChoose)
                IgnorePointer(
                  child: KqCheckBox(
                    value: _chooseItems.contains(item),
                  ),
                ),
              if (widget.isMultiChoose)
                SizedBox(
                  width: 4.r,
                ),
              Expanded(child: Text(
                title,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    fontSize: widget.fontSize ?? 16.sp,
                    color: KqThemeManager.instance
                        .getConfig()
                        .dialogConfig
                        .itemTextColor ??
                        KqThemeColors.text26),
              )),
            ],
          ),
        ),
      ));
      if (i < (_showItems.length - 1)) {
        children.add(const KqDivider());
      }
    }

    Widget dialogChild = Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: children,
    );
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (widget.searchEnable)
          Container(
            margin: EdgeInsets.only(
              left: 16.r,
              right: 16.r,
            ),
            child: ClipRRect(
              borderRadius:
                  BorderRadius.all(Radius.circular(widget.radius ?? 4.r)),
              child: KqSearchBar(
                newValue: _searchText,
                onChanged: (value) {
                  _searchText = value;
                  searchData();
                },
                innerBgColor: Colors.transparent,
                onCancel: () {
                  _searchText = "";
                  searchData();
                },
                onCleared: () {
                  _searchText = "";
                  searchData();
                },
              ),
            ),
          ),
        if (widget.searchEnable)
          SizedBox(
            height: 8.r,
          ),
        Container(
          margin: EdgeInsets.only(
              left: 16.r, right: 16.r, bottom: widget.isMultiChoose ? 0 : 16.r),
          child: ClipRRect(
            borderRadius:
                BorderRadius.all(Radius.circular(widget.radius ?? 4.r)),
            child: Container(
              color: KqThemeManager.instance.getConfig().dialogConfig.bgColor ??
                  KqThemeColors.bgWhite,
              child: LimitedBox(
                maxHeight: KqScreenUtil().screenHeight -
                    138.r -
                    52.r -
                    (widget.isMultiChoose
                        ? 64.r + 8.r + KqScreenUtil().bottomBarHeight
                        : 0) -
                    widget.paddingBottom,
                child: SingleChildScrollView(
                  child: dialogChild,
                ),
              ),
            ),
          ),
        ),
        if (widget.isMultiChoose) _buildBottom(),
      ],
    );
  }

  _buildBottom() {
    return Container(
      color: KqThemeColors.bgWhite,
      margin: EdgeInsets.only(top: 8.r),
      padding: EdgeInsets.only(
          top: 8.r, bottom: 8.r + KqScreenUtil().bottomBarHeight),
      child: Row(
        children: [
          LimitedBox(
            maxWidth: 90.r,
            child: SizedBox(
              height: 48.r,
              child: KqInkWell(
                  onTap: () {
                    if (_isChooseAll) {
                      //全不选
                      _chooseItems = [];
                      _isChooseAll = false;
                    } else {
                      //全选
                      List<T> list = [];
                      for (var i = 0; i < _showItems.length; i++) {
                        list.add(_showItems[i]);
                      }
                      _chooseItems = list;
                      _isChooseAll = true;
                    }
                    setState(() {});
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      IgnorePointer(
                        child: KqCheckBox(
                          value: _isChooseAll,
                          width: 16.r,
                          height: 16.r,
                        ),
                      ),
                      SizedBox(width: 4.r),
                      Text(
                        KqIntl.currentResource.selectAll,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            color: KqThemeColors.text26, fontSize: 14.sp),
                      ),
                    ],
                  )),
            ),
          ),
          Expanded(
              child: Container(
            clipBehavior: Clip.hardEdge,
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(4.r)),
            child: KqInkWell(
                onTap: () {
                  //确定
                  if (widget.callbackMulti != null) {
                    widget.callbackMulti!.call(
                        _chooseItems, _isChooseAll && _searchText.isEmpty);
                  }
                },
                backgroundColor: KqThemeColors.textBlue,
                child: Container(
                  height: 48.r,
                  alignment: Alignment.center,
                  child: Text(
                    KqIntl.currentResource.ok,
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.white, fontSize: 16.sp),
                  ),
                )),
          )),
          SizedBox(width: 16.r),
        ],
      ),
    );
  }

  void searchData({bool update = true}) {
    if (_searchText.isEmpty) {
      _showItems = [..._allItems];
    } else {
      _showItems.clear();
      for (T item in _allItems) {
        bool showItem = widget.onSearchItem?.call(_searchText, item) ?? true;
        if (showItem) {
          _showItems.add(item);
        }
      }
    }
    if (update) {
      setState(() {});
    }
  }
}
